#include "glbackgroundprogram.h"

GLBackgroundProgram::GLBackgroundProgram(const QString &vertex, const QString &fragment, QObject *parent)
    : QOpenGLShaderProgram(parent)
{
    vShader = new QOpenGLShader(QOpenGLShader::Vertex, this);
    fShader = new QOpenGLShader(QOpenGLShader::Fragment, this);
    vShader->compileSourceFile(vertex);
    fShader->compileSourceFile(fragment);
    this->addShader(vShader);
    this->addShader(fShader);
    this->link();
    this->setBackGround();
}

GLBackgroundProgram::~GLBackgroundProgram()
{
    locationHash.clear();
    backgroundVertex.clear();
}

void GLBackgroundProgram::setLocation()
{
    int temp = 0;
    temp = this->attributeLocation("pos");
    locationHash.insert("pos", temp);
    temp = this->uniformLocation("currentColor");
    locationHash.insert("currentColor", temp);
}

int GLBackgroundProgram::getLocation(const QString &key)
{
    return locationHash.value(key);
}

int GLBackgroundProgram::getBackgroundVertexSize()
{
    return backgroundVertex.size() / 2;
}

const GLfloat *GLBackgroundProgram::getBackgroundVertexData()
{
    return backgroundVertex.data();
}

void GLBackgroundProgram::setBackGround()
{
    backgroundVertex.clear();
    for (int i = 1; i < LARGE_SECTION_X; i++) {
        GLfloat xPos = 2.0 * i / LARGE_SECTION_X - 1.0;
        GLfloat yPos = 0.0;
        for (int j = 1; j < LARGE_SECTION_Y; j++) {
            yPos = 2.0 * j / LARGE_SECTION_Y - 1.0;
            backgroundVertex.push_back(xPos);
            backgroundVertex.push_back(yPos);
        }
    }

    for (int i = 1; i < LARGE_SECTION_X; i++) {
        GLfloat xPos = 2.0 * i / LARGE_SECTION_X - 1.0;
        GLfloat yPos = 0.0;
        int section = LARGE_SECTION_Y * LITTLE_SECTION_Y;
        for (int j = 0; j < LARGE_SECTION_Y; j++) {
            for (int k = 1; k < LITTLE_SECTION_Y; k++) {
                yPos = 2.0 * (j * LITTLE_SECTION_Y + k) / section - 1.0;
                backgroundVertex.push_back(xPos);
                backgroundVertex.push_back(yPos);
            }
        }
    }

    for (int i = 1; i < LARGE_SECTION_Y; i++) {
        GLfloat yPos = 2.0 * i / LARGE_SECTION_Y - 1.0;
        GLfloat xPos = 0.0;
        int section = LARGE_SECTION_X * LITTLE_SECTION_X;
        for (int j = 0; j < LARGE_SECTION_X; j++) {
            for (int k = 1; k < LITTLE_SECTION_X; k++) {
                xPos = 2.0 * (j * LITTLE_SECTION_X + k) / section - 1.0;
                backgroundVertex.push_back(xPos);
                backgroundVertex.push_back(yPos);
            }
        }
    }
}
